<template>
  <div style="height: 100%;background-color:white ;">
    <el-row>
      <el-col :span="9">
        <el-button :style="{ display: checkAllEnable }" @click="releaseSelection()" size="small" type="success">流程图发布
        </el-button>
        <el-button :style="{ display: checkAllEnable }" @click="releaseAll()" size="small" type="success">一键发布
        </el-button>
        <el-button v-if="radioStatus === 'published' && detailStatus==='false'" plain size="small"
                   type="success" @click="multiRevise('multi')">
          批量修订
        </el-button>
        <el-button v-if="radioStatus === 'published' && detailStatus==='false'" plain size="small"
                   type="success" @click="multiRevise('all')">一键修订
        </el-button>
        <el-button v-if="radioStatus === 'published' && detailStatus==='false'" size="small"
                   type="success" @click="multipleExportFlowChart">批量导出
        </el-button>
        <el-button v-if="radioStatus === 'published' && detailStatus==='false'" size="small" type="success"
                   @click="allExportFlowChart('')">一键导出
        </el-button>
        <el-button v-if="radioStatus === 'published' && detailStatus==='false'" plain size="small" type="info"
                   @click="recycleSite">回收站
        </el-button>
        <div style="display: inline-block">
          <div style="display: inline-block"><span></span></div>
        </div>
      </el-col>
      <el-col :span="6">
        <el-radio-group @change="valueChange()" size="small" style="margin-left: 140px;" v-model="radioStatus">
          <el-radio-button v-if="detailStatus!='true'" label="unpublished">未发布</el-radio-button>
          <el-radio-button v-if="detailStatus!='true'" label="published">发布</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="9">
        <div>
          <div style="width: 430px; float: right">
            <el-input @keyup.enter.native="searchEnterFun($event)"
                      placeholder="请输入名称"
                      v-model="flowName">
              <i class="el-input__icon el-icon-search"
                 slot="prefix"></i>
              <el-button :icon="appendIcon"
                         slot="append"
                         v-on:click="switchAppend"></el-button>
            </el-input>
          </div>
          <div id="advance"
               style="padding: 10px; float: right;"
               v-if="showAdvance">
            <div>
              <div style="margin-top: 20px; display: flex;">
                <div class="advancedSearchLabel">创建人</div>
                <div style="width: 217px">
                  <el-select
                    v-model="createdBy"
                    clearable
                    filterable
                    placeholder="请输入创建人"
                    size="small">
                    <el-option
                      v-for="item in $store.state.userList"
                      :key="item.userName"
                      :label="item.name"
                      :value="item.userName">
                    </el-option>
                  </el-select>
                </div>
              </div>
            </div>
            <div>
              <div style="margin-top: 10px; display: flex;">
                <div class="advancedSearchLabel">版本号</div>
                <div style="width: 217px">
                  <el-input placeholder="请输入版本号" size="small" style="width: 300px" v-model="version"></el-input>
                </div>
              </div>
            </div>
            <div>
              <div style="margin-top: 10px; display: flex;">
                <div class="advancedSearchLabel">归属项目</div>
                <div style="width: 217px">
                  <el-cascader :options="itemOptions"
                               :props="cascadeProps"
                               :show-all-levels="false"
                               @change="handleChange"
                               clearable
                               placeholder="归属项目"
                               size="small"
                               style="width: 300px"
                               v-model="belongingItems">
                  </el-cascader>
                </div>
              </div>
            </div>
            <div>
              <div style="margin-top: 10px; display: flex;">
                <div class="advancedSearchLabel">科学分类</div>
                <div style="width: 300px">
                  <el-cascader :options="scienceItemOptions"
                               :props="cascadeProps"
                               :show-all-levels="false"
                               @change="scienceHandleChange"
                               clearable
                               placeholder="科学分类"
                               size="small"
                               style="width: 300px" v-model="scienceItems"></el-cascader>
                </div>
              </div>
            </div>
            <div class="block" style="margin-top: 10px; display: flex;">
              <div class="advancedSearchLabel">操作时间</div>
              <div class="block" style="display: inline-block;">
                <el-date-picker
                  @change="dateChange"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  size="small"
                  start-placeholder="开始日期"
                  style="width: 300px;" type="datetimerange"
                  v-model="createdTime" value-format=" yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </div>
            </div>
            <div class="block" style="margin-top: 10px; display: flex;">
              <div class="advancedSearchLabel">是否修订</div>
              <div class="block" style="display: inline-block;">
                <el-select v-model="isRevised" clearable filterable size="small" style="width: 300px">
                  <el-option label="否" value="1">否</el-option>
                  <el-option label="是" value="2">是</el-option>
                </el-select>
              </div>
            </div>
            <div style="margin-top: 30px; right: 10px;">
              <el-row>
                <el-col :offset="6" :span="6">
                  <div style="margin-left: 90px;height: 32px; width: 88px;">
                    <el-button size="small" v-on:click="advanceCancel">取 消
                    </el-button>
                  </div>
                </el-col>
                <el-col :offset="2" :span="2">
                  <div style="margin-left: 30px;height: 32px; width: 88px;">
                    <el-button size="small" v-on:click="reset">重置</el-button>
                  </div>
                </el-col>
                <el-col :offset="2" :span="2">
                  <div style="margin-left: 30px;height: 32px; width: 88px;">
                    <el-button size="small" type="success" v-on:click="advanceConfirm">确 定</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row style="margin-top: 10px;">
      <el-col :span="24">
        <el-table :data="tableData" :height="tableHeight" border
                  highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            v-model="multipleSelection"
            width="55">
          </el-table-column>
          <el-table-column label="名称"
                           min-width="180"
                           prop="flowName"></el-table-column>
          <el-table-column label="归属项目"
                           min-width="100"
                           prop="belongingItemId">
            <template slot-scope="scope">
              {{ getBelongingItemNameById(scope.row.belongingItemId) }}
            </template>
          </el-table-column>
          <el-table-column label="科学分类"
                           min-width="100"
                           prop="scienceTagId">
            <template slot-scope="scope">
              {{ getScienceItemNameById(scope.row.scienceTagId) }}
            </template>
          </el-table-column>
          <el-table-column label="版本号"
                           min-width="100"
                           prop="version"></el-table-column>
          <el-table-column label="创建人"
                           min-width="80"
                           prop="createdBy">
            <template slot-scope="scope">
              {{ getNameByUserName(scope.row.createdBy) }}
            </template>
          </el-table-column>
          <el-table-column v-if="this.radioStatus==='published'" label="是否修订" min-width="100" prop="isRevised"
                           show-overflow-tooltip
                           width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.isRevised=='1'">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column :formatter="dateFormat"
                           label="创建时间"
                           min-width="140"
                           prop="createdTime"></el-table-column>
          <el-table-column label="操作"
                           :show-overflow-tooltip="false" min-width="150">
            <template slot-scope="scope">
                <span><el-link :style="{ display: editEnable }" type="primary"
                               @click.prevent="exportFlowChart(scope.row.id)">导出</el-link></span>
              <span><el-link :style="{ display:releaseEnable }"
                             type="primary"
                             @click.prevent="release(scope.row.id,scope.row.flowName)">发布</el-link></span>
              <span><el-link @click.prevent="showLog(scope.row.id)" type="primary">日志</el-link></span>
              <span><el-link @click.prevent="mobile(scope.row.id)" type="primary">详情</el-link></span>
              <span><el-link :style="{ display: editEnable }" @click.prevent="revise(scope.row)"
                             type="primary">修订</el-link></span>
              <span><el-link :style="{ display: editEnable }" @click.prevent="update(scope.row.id)"
                             type="primary">勘误</el-link></span>
              <span><el-link :style="{ display:releaseEnable }"
                             type="primary"
                             @click.prevent="reject(scope.row.id)">驳回</el-link></span>
              <span><el-link :style="{display: editEnable}" type="danger"
                             @click.prevent="del(scope.row.id)">删除</el-link></span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-pagination
        v-if="multiplePages"
        :page-size="pageSize"
        :page-sizes="[5, 10, 15, 20, 50, 100]"
        :total="totalNum"
        background
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right;margin-top: 10px"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"></el-pagination>
    </el-row>
    <el-dialog :visible.sync="selectTaskDialogVisible" title="新建子任务" width="500px">
      <el-row>
        <el-col :span="6">
          <span class="label">选择任务<em style="color: red">*</em></span>
        </el-col>
        <el-col :span="18">
          <el-select filterable v-model="selectedTaskId" style="width: 100%"
                     placeholder="请选择">
            <el-option
              v-for="(item,index) in taskList"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">备注</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model.trim="taskItemRemark"/>
        </el-col>
      </el-row>
      <span class="dialog-footer" slot="footer">
        <el-button @click="closeSelectTaskDialog">取 消</el-button>
        <el-button @click="insertTaskItem" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";

export default {
  name: "ReleasedFlowChart",
  components: {},
  props: ["detailStatus"],
  data() {
    return {
      tableData: [],
      tableHeight: '',
      multipleSelection: [],
      totalNum: 0,
      currentPage: 1, // 第几页
      pageSize: 10, // 每页显示的数据个数
      multiplePages: true,
      appendIcon: "el-icon-caret-bottom",
      showAdvance: false,
      itemOptions: [],
      scienceItemOptions: [],
      belongingItems: "",
      scienceItems: "",
      radioStatus: '',
      cascadeProps: {multiple: false},
      flowName: "",
      createdBy: "",
      createdTime: '',
      version: '',
      status: '',
      content1: '',
      releaseEnable: '',
      editEnable: 'none',
      checkAllEnable: '',
      delEnable: '',
      selectedFlowChart: {},
      taskList: [],
      selectTaskDialogVisible: false,
      selectedTaskId: '',
      taskItemRemark: '',
      isRevised: ''
    }
  },
  methods: {
    recycleSite() {
      this.$router.push({
          path: '/flowChartRecycle',
        }
      )
    },
    del(id) {
      this.axios.get('/pmph/action/task/selectTaskItemInProcessByKnowledgeId', {
        params: {
          knowledgeId: id,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.$message.warning("当前知识正在修订中, 请先删除修订中的知识");
        } else {
          this.$confirm('是否删除？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteReleaseFlowChart(id)
          })
        }
      })
    },
    deleteReleaseFlowChart(id) {
      this.axios.get('/pmph/action/flowChartAction/deleteReleaseFlowChartById', {
        params: {
          id: id,
          status: "published"
        }
      }).then((response) => {
        this.getTableData()
        this.$emit("released")
      })
    },
    insertTaskItem() {
      if (!this.selectedTaskId) {
        this.$message.warning("请选择挂载任务")
        return
      }
      // 单条数据修订;
      if (this.reviseType === 'single') {
        let param = new URLSearchParams();
        param.append("taskItem", JSON.stringify({
          taskId: this.selectedTaskId,
          name: this.selectedFlowChart.flowName,
          knowledgeId: this.selectedFlowChart.id,
          type: CONST.TASK_ITEM.TYPE_EDIT,
          remark: this.taskItemRemark,
        }))
        this.axios.post('/pmph/action/task/saveTaskItem', param)
          .then(() => {
            this.closeSelectTaskDialog()
          })
      }
      // 批量/一键修订;
      else {
        let param = new URLSearchParams();
        param.append("reviseType", this.reviseType)
        param.append("selectedKnowledgeIds", JSON.stringify(this.multipleSelection.map(item => item.id)))
        param.append("taskId", this.selectedTaskId)
        param.append("remark", this.taskItemRemark)
        param.append('searchParams', JSON.stringify({
          createdBy: this.createdBy,
          flowName: this.flowName,
          belongingItemId: this.belongingItems.toString(),
          scienceItemId: this.scienceItems.toString(),
          status: this.radioStatus,
          createdTime: this.createdTime.toString(),
          version: this.version,
          isRevised: this.isRevised

        }));
        this.axios.post('/pmph/action/flowChartAction/multiInsertTaskItem', param)
          .then(() => {
            this.closeSelectTaskDialog()
            setTimeout(this.getTableData, 3000);

          })
      }
    },
    closeSelectTaskDialog() {
      this.selectTaskDialogVisible = false
      this.taskList = []
      this.taskItemRemark = ''
    },
    valueChange: function () {
      if (this.radioStatus === 'unpublished') {
        this.editEnable = 'none'
        this.delEnable = ''
        this.checkAllEnable = ''
        this.releaseEnable = ''
      } else {
        this.editEnable = ''
        this.delEnable = 'none'
        this.checkAllEnable = 'none'
        this.releaseEnable = 'none'
      }
      this.getTableData();
    },
    //复选框选中事件
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
      console.log(this.multipleSelection)
    },
    //时间处理
    dateFormat: function (row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format("YYYY-MM-DD  HH:mm:ss")
    },
    advanceCancel: function () {
      this.showAdvance = false;
    },
    advanceConfirm: function () {
      this.currentPage = 1;
      this.showAdvance = false;
      this.getTableData();
    },
    switchAppend: function () {
      if (this.showAdvance) {
        this.showAdvance = false;
        this.appendIcon = "el-icon-caret-bottom";
      } else {
        this.showAdvance = true;
        this.appendIcon = "el-icon-caret-top";
      }
    },
    update: function (val) {
      this.$emit("updateById", val);
      let routeUrl = this.$router.resolve({
        path: "/knowledgeLib/MakeFlowChart",
        query: {id: val, status: this.radioStatus, showStatus: 'released', enableCreate: '1'},
      });
      window.open(routeUrl.href, "_blank");
    },
    searchEnterFun(e) {
      const keyCode = window.event ? e.keyCode : e.which;
      console.log("回车搜索", keyCode, e);
      if (keyCode === 13) {
        this.currentPage = 1;
        this.getTableData();
      }
    },
    reset: function () {
      this.flowName = "";
      this.createdBy = "";
      this.belongingItems = "";
      this.scienceItems = "";
      this.createdTime = "";
      this.version = "";
      this.isRevised = "";
    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.getTableData();
    },
    handleChange(value) {
      this.belongingItems = value;
    },
    scienceHandleChange(value) {
      this.scienceItems = value;
    },
    dateChange(val) {
      this.createdTime = val;
      if (val == null) {
        this.createdTime = ''
      }
    },
    showLog: function (id) {
      this.$router.push({
        path: '/flowChartLog',
        query: {id: id},
      })
    },
    mobile(id) {
      let routeUrl = this.$router.resolve({
        path: "/flowchart/mobileViewFlowChart",
        query: {id: id, status: this.radioStatus},
      });
      window.open(routeUrl.href, "_blank");
    },
    getTableData: function () {
      console.log(this.isRevised)
      let url = ''
      if (this.radioStatus === 'unpublished') {
        url = '/pmph/action/flowChartAction/selectFlowCharList'
      } else {
        url = '/pmph/action/flowChartAction/selectReleasedFlowCharList'
      }
      this.axios.get(url, {
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          createdBy: this.createdBy,
          flowName: this.flowName,
          belongingItemId: this.belongingItems.toString(),
          scienceTagId: this.scienceItems.toString(),
          queryCreatedTime: this.createdTime.toString(),
          version: this.version,
          isRevised: this.isRevised
        },
      }).then((response) => {
        this.noData = response.data.total <= 0;
        this.tableData = response.data.records;
        this.totalNum = response.data.total;
      });
    },
    multipleExportFlowChart() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请选中需要导出的流程图")
        return
      }
      // 选中的id集合;
      let ids = this.multipleSelection.map(item => item.id).join(",");
      this.exportFlowChart(ids);
    },
    allExportFlowChart(id) {
      this.exportFlowChart(id)
    },
    exportFlowChart(ids) {
      this.axios.get('/pmph/action/flowChartAction/exportFlowChart', {
        params: {
          createdBy: this.createdBy,
          flowName: this.flowName,
          belongingItemId: this.belongingItems.toString(),
          scienceItemId: this.scienceItems.toString(),
          status: this.radioStatus,
          createdTime: this.createdTime.toString(),
          version: this.version,
          ids: ids
        },
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/zip'
        }
      }).then((response) => {
        this.downloadFile(response.data);
      })
    },
    downloadFile(data) {
      // 文件导出
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data], {type: "application/zip"}));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', 'export.zip');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放blob对
    },
    //发布——单个
    release: function (id, name) {
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = new URLSearchParams();
        param.append("id", id)
        param.append("name", name)
        this.axios.post('/pmph/action/flowChartAction/selectFlowChartToReleasedFlowChart', param)
          .then((response) => {
            this.getTableData()
            this.$emit("released")
          });
      })
    },
    releaseSelection: function () {
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = new URLSearchParams();
        param.append("selection", JSON.stringify(this.multipleSelection))
        this.axios.post('/pmph/action/flowChartAction/selectionFlowChartToReleased', param)
          .then((response) => {
            this.getTableData()
            this.$emit("released")
          });
      })
    },
    releaseAll: function () {
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/pmph/action/flowChartAction/getAllFlowChartToReleased', {
          params: {
            createdBy: this.createdBy,
            flowName: this.flowName,
            belongingItemId: this.belongingItems.toString(),
            scienceItemId: this.scienceItems.toString(),
            status: this.radioStatus,
            createdTime: this.createdTime.toString()
          }
        }).then((response) => {
          const that = this;
          this.getTableData(that, this.radio1)
          this.$emit("released")
        });
      })
    },
    revise: async function (flowChart) {
      this.reviseType = 'single'
      this.selectedFlowChart = flowChart
      let checkFlag = false
      // 查询本知识是否已和正在进行中的子任务关联
      await this.axios.get('/pmph/action/task/selectTaskItemInProcessByKnowledgeId', {
        params: {
          knowledgeId: flowChart.id,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.$message.warning("当前流程图正在修订中, 请勿重复修订")
        } else {
          checkFlag = true
        }
      })
      if (checkFlag) {
        // 查询当前知识库关联正在进行中的任务, 供用户选择
        this.axios.get('/pmph/action/task/selectTaskInProcessByKnowledgeLibId', {
          params: {
            knowledgeLibId: CONST.KNOWLEDGE_LIB.FLOW_CHART_LIB_ID,
          }
        }).then((response) => {
          if (response.data.length > 0) {
            this.taskList = response.data
            this.selectTaskDialogVisible = true
          } else {
            this.$message.warning("流程图没有正在进行中的任务, 请先新建任务!")
          }
        })
      }
    },
    multiRevise: function (reviseType) {
      this.reviseType = reviseType
      if (reviseType === 'multi' && this.multipleSelection.length === 0) {
        this.$message.warning("请选择修订的流程图!")
        return
      }
      // 查询当前知识库关联正在进行中的任务, 供用户选择
      this.axios.get('/pmph/action/task/selectTaskInProcessByKnowledgeLibId', {
        params: {
          knowledgeLibId: CONST.KNOWLEDGE_LIB.FLOW_CHART_LIB_ID,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.taskList = response.data
          this.selectTaskDialogVisible = true
        } else {
          this.$message.warning("计算器没有正在进行中的任务, 请先新建任务!")
        }
      })
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.getTableData()
    },
    reject(id) {
      this.$confirm('此操作将使子任务状态退回到最后一步审核状态，是否确定这样做？', '请确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.$prompt('请输入驳回原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '驳回原因不能为空'
        }).then(({value}) => {
          this.axios.get("/pmph/action/task/cancelAudit", {
            params: {
              id: id,
              reason: value
            }
          }).then(() => {
            this.getTableData()
          })
        })
      })
    },
    getNameByUserName(userName) {
      return this.$store.state.userList.filter(item => item.userName === userName)[0].name;
    },
    getBelongingItemNameById(id) {
      return this.$store.state.ruleList.filter(item => item.id === '11')[0].ruleItemList
        .filter(item => item.id === id)[0].name;
    },
    getScienceItemNameById(id) {
      return this.$store.state.ruleList.filter(item => item.id === '13')[0].ruleItemList
        .filter(item => item.id === id)[0].name;
    }
  },
  activated() {
    this.getTableData();
  },
  created() {
    window.addEventListener("visibilitychange", (e) => {
      if (document.visibilityState !== "hidden") {
        this.getTableData();
      }
    });
    if (this.detailStatus === 'true') {
      this.radioStatus = 'published'
      this.editEnable = 'none'
      this.checkAllEnable = 'none'
      this.releaseEnable = 'none'
    } else {
      this.radioStatus = 'unpublished'
    }
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 160;
    this.getTableData()
    // 获取分类数据
    this.axios
      .get("/pmph/action/flowChartAction/selectBelongingItemsData")
      .then((response) => {
        this.itemOptions = response.data;
      })
      .catch((error) => {
        this.$message.error("获取归属项目数据失败");
      });

    // 获取分类数据
    this.axios
      .get("/pmph/action/flowChartAction/selectScienceData")
      .then((response) => {
        this.scienceItemOptions = response.data;
      })
      .catch((error) => {
        this.$message.error("获取科学分类数据失败");
      });

  }
}
</script>

<style scoped>

</style>
